<!DOCTYPE html>
<html lang="zh">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>管理员界面</title>
    <style>
        /* 全局样式 */
        body {
            font-family: "Arial", sans-serif;
            margin: 0;
            padding: 0;
            background: linear-gradient(to bottom right, #e0f7fa, #00695c);
            height: 100vh;
            display: flex;
            justify-content: center;
            align-items: center;
        }

        .container {
            display: flex;
            height: 90%;
            width: 90%;
            background: #ffffff;
            border-radius: 12px;
            box-shadow: 0 10px 20px rgba(0, 0, 0, 0.2);
            overflow: hidden;
            position: relative;
        }

        /* 左侧导航栏 */
        .sidebar {
            background-color: #004d40;
            color: white;
            width: 240px;
            padding: 20px;
            display: flex;
            flex-direction: column;
        }

        .sidebar h2 {
            font-size: 22px;
            text-align: center;
            margin-bottom: 20px;
            color: #e0f7fa;
            font-weight: bold; /* 加粗 */
        }

        .sidebar a {
            color: #e0f7fa;
            text-decoration: none;
            margin: 10px 0;
            font-size: 18px;
            padding: 12px;
            border-radius: 8px;
            cursor: pointer;
            transition: all 0.3s ease;
            font-weight: bold; /* 加粗 */
        }

        .sidebar a:hover {
            background-color: #00796b;
            color: #ffffff;
        }

        /* 右侧内容区域 */
        .main-content {
            flex: 1;
            padding: 20px;
            background-color: #f9f9f9;
            overflow-y: auto;
            position: relative;
        }

        .main-content h3 {
            font-size: 24px;
            margin-bottom: 20px;
            color: #004d40;
            font-weight: bold; /* 加粗 */
        }

        table {
            width: 100%;
            border-collapse: collapse;
            margin-top: 20px;
            background-color: rgba(255, 255, 255, 0.9); /* 半透明背景色 */
            border-radius: 8px;
            overflow: hidden;
            position: relative;
        }

        th, td {
            padding: 12px;
            border: 1px solid #e0e0e0;
            text-align: center;
            font-size: 16px;
            font-weight: bold; /* 加粗 */
        }

        th {
            background-color: #004d40;
            color: white;
        }

        tr:nth-child(even) {
            background-color: rgba(240, 240, 240, 0.9); /* 半透明背景 */
        }

        .btn {
            padding: 8px 16px;
            font-size: 14px;
            border: none;
            border-radius: 5px;
            cursor: pointer;
            transition: all 0.3s ease;
            font-weight: bold; /* 加粗 */
        }

        .btn.edit {
            background-color: #4caf50;
            color: white;
        }

        .btn.edit:hover {
            background-color: #43a047;
        }

        .btn.delete {
            background-color: #f44336;
            color: white;
        }

        .btn.delete:hover {
            background-color: #e53935;
        }

        /* 底部背景图片 */
        .main-content::after {
            content: "";
            position: absolute;
            top: 0; /* 从顶部开始 */
            left: 0;
            right: 0;
            bottom: 0; /* 填充整个区域 */
            background: url('../static/img/装饰.png') no-repeat center;
            background-size: cover; /* 让图片完全覆盖 */
            opacity: 0.3; /* 图片透明度降低，防止影响阅读 */
            pointer-events: none; /* 禁止干扰鼠标操作 */
        }

        /* 弹窗样式 */
        .form-popup {
            display: none;
            position: fixed;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%);
            background-color: white;
            padding: 30px;
            box-shadow: 0 10px 20px rgba(0, 0, 0, 0.3);
            border-radius: 10px;
            z-index: 1000;
        }

        .form-popup input, .form-popup textarea, .form-popup button, .form-popup select {
            margin: 12px 0;
            width: 100%;
            padding: 10px;
            border: 1px solid #ddd;
            border-radius: 6px;
            font-size: 14px;
        }

        .form-popup button {
            background-color: #00796b;
            color: white;
            border: none;
            cursor: pointer;
            font-weight: bold; /* 加粗 */
        }

        .form-popup button:hover {
            background-color: #004d40;
        }

        .form-popup .cancel-btn {
            background-color: #f44336;
            color: white;
            font-weight: bold; /* 加粗 */
        }

        .form-popup .cancel-btn:hover {
            background-color: #d32f2f;
        }
    </style>
</head>
<body>
    <div class="container">
        <!-- 左侧导航栏 -->
        <div class="sidebar">
            <h2>管理员系统</h2>
            <a onclick="loadUsers()">用户信息</a>
            <a onclick="loadCrops()">作物信息</a>
            <a onclick="loadLogs()">日志信息</a>
            <a onclick="loadPests()">害虫信息</a>
            <a onclick="loadInspections()">检测记录</a>
        </div>

        <!-- 右侧内容区域 -->
        <div class="main-content" id="content">
            <h3>用户信息</h3>
            <table>
                <thead>
                    <tr>
                        <th>ID</th>
                        <th>用户名</th>
                        <th>邮箱</th>
                        <th>角色</th>
                        <th>操作</th>
                    </tr>
                </thead>
                <tbody>
                    <!-- 示例数据 -->
                    <tr>
                        <td>1</td>
                        <td>lijunyi</td>
                        <td>lijy727@mail2.sysu.edu.cn</td>
                        <td>planter</td>
                        <td>
                            <button class="btn edit">编辑</button>
                            <button class="btn delete">删除</button>
                        </td>
                    </tr>
                </tbody>
            </table>
        </div>
    </div>

    <!-- 弹窗 -->
    <div class="form-popup" id="form-popup">
        <h3 id="form-title">编辑用户</h3>
        <form id="edit-form">
            {% csrf_token %}
            <div id="form-fields">
                <!-- 表单字段 -->
            </div>
            <button type="submit">提交</button>
            <button type="button" class="cancel-btn" onclick="closeForm()">取消</button>
        </form>
    </div>
</body>
</html>




    <!-- 引入外部 JavaScript 文件 -->
        <script>
                let currentView = "";

function showForm(title, fieldsHTML) {
    document.getElementById("form-title").innerText = title;
    document.getElementById("form-fields").innerHTML = fieldsHTML;
    document.getElementById("form-popup").style.display = "block";
}

function closeForm() {
    document.getElementById("form-popup").style.display = "none";
}

// 加载用户信息
function loadUsers() {
    currentView = "user";
    fetch("/get_users/")
        .then(response => response.json())
        .then(data => {
            let tableHTML = `
                <h2>用户信息</h2>
                <button onclick="prepareAddUserForm()">添加用户</button>
                <table>
                    <tr>
                        <th>ID</th>
                        <th>用户名</th>
                        <th>邮箱</th>
                        <th>角色</th>
                        <th>操作</th>
                    </tr>
            `;
            data.data.forEach(user => {
                tableHTML += `
                    <tr>
                        <td>${user.id}</td>
                        <td>${user.username}</td>
                        <td>${user.email}</td>
                        <td>${user.role}</td>
                        <td>
                            <button onclick="editUser(${user.id})">编辑</button>
                            <button onclick="deleteUser(${user.id})">删除</button>
                        </td>
                    </tr>
                `;
            });
            tableHTML += `</table>`;
            document.getElementById("content").innerHTML = tableHTML;
        });
}

function prepareAddUserForm() {
    const fields = `
        <input type="text" name="username" placeholder="用户名" required>
        <input type="email" name="email" placeholder="邮箱" required>
        <select name="role" required>
            <option value="admin">管理员</option>
            <option value="planter">种植员</option>
            <option value="inspector">检测员</option>
        </select>
        <input type="password" name="password" placeholder="密码" required>
    `;
    showForm("添加用户", fields);
    document.getElementById("edit-form").onsubmit = addUser;
}

function addUser(event) {
    event.preventDefault();
    const csrfToken = document.querySelector("[name=csrfmiddlewaretoken]").value;
    const formData = new FormData(event.target);
    const data = Object.fromEntries(formData.entries());

    fetch("/add_user/", {
        method: "POST",
        headers: {
            "Content-Type": "application/json",
            "X-CSRFToken": csrfToken
        },
        body: JSON.stringify(data)
    }).then(() => {
        closeForm();
        loadUsers();
    });
}

function editUser(id) {
    fetch(`/get_user/${id}/`)
        .then(response => response.json())
        .then(user => {
            const fields = `
                <input type="text" name="username" value="${user.username}" required>
                <input type="email" name="email" value="${user.email}" required>
                <select name="role" required>
                    <option value="admin" ${user.role === "admin" ? "selected" : ""}>管理员</option>
                    <option value="planter" ${user.role === "planter" ? "selected" : ""}>种植员</option>
                    <option value="inspector" ${user.role === "inspector" ? "selected" : ""}>检测员</option>
                </select>
            `;
            showForm("编辑用户", fields);
            document.getElementById("edit-form").onsubmit = function(event) {
                event.preventDefault();
                updateUser(id);
            };
        });
}

function updateUser(id) {
    const csrfToken = document.querySelector("[name=csrfmiddlewaretoken]").value;
    const formData = new FormData(document.getElementById("edit-form"));
    const data = Object.fromEntries(formData.entries());

    fetch(`/update_user/${id}/`, {
        method: "PUT",
        headers: {
            "Content-Type": "application/json",
            "X-CSRFToken": csrfToken
        },
        body: JSON.stringify(data)
    }).then(() => {
        closeForm();
        loadUsers();
    });
}

function deleteUser(id) {
    const csrfToken = document.querySelector("[name=csrfmiddlewaretoken]").value;

    fetch(`/delete_user/${id}/`, {
        method: "DELETE",
        headers: { "X-CSRFToken": csrfToken }
    }).then(() => loadUsers());
}

// 加载作物信息
function loadCrops() {
    currentView = "crop";
    fetch("/get_crops/")
        .then(response => response.json())
        .then(data => {
            let tableHTML = `
                <h2>作物信息</h2>
                <button onclick="prepareAddCropForm()">添加作物</button>
                <table>
                    <tr>
                        <th>ID</th>
                        <th>名称</th>
                        <th>类型</th>
                        <th>种植日期</th>
                        <th>位置</th>
                        <th>操作</th>
                    </tr>
            `;
            data.data.forEach(crop => {
                tableHTML += `
                    <tr>
                        <td>${crop.id}</td>
                        <td>${crop.name}</td>
                        <td>${crop.crop_type}</td>
                        <td>${crop.planting_date}</td>
                        <td>${crop.location}</td>
                        <td>
                            <button onclick="editCrop(${crop.id})">编辑</button>
                            <button onclick="deleteCrop(${crop.id})">删除</button>
                        </td>
                    </tr>
                `;
            });
            tableHTML += `</table>`;
            document.getElementById("content").innerHTML = tableHTML;
        });
}

function prepareAddCropForm() {
    const fields = `
        <input type="text" name="name" placeholder="名称" required>
        <input type="text" name="crop_type" placeholder="类型" required>
        <input type="date" name="planting_date" placeholder="种植日期" required>
        <input type="text" name="location" placeholder="位置" required>
    `;
    showForm("添加作物", fields);
    document.getElementById("edit-form").onsubmit = addCrop;
}

function addCrop(event) {
    event.preventDefault();
    const csrfToken = document.querySelector("[name=csrfmiddlewaretoken]").value;
    const formData = new FormData(event.target);
    const data = Object.fromEntries(formData.entries());

    fetch("/add_crop/", {
        method: "POST",
        headers: {
            "Content-Type": "application/json",
            "X-CSRFToken": csrfToken
        },
        body: JSON.stringify(data)
    }).then(() => {
        closeForm();
        loadCrops();
    });
}

function editCrop(id) {
    fetch(`/get_crop/${id}/`)
        .then(response => response.json())
        .then(crop => {
            const fields = `
                <input type="text" name="name" value="${crop.name}" required>
                <input type="text" name="crop_type" value="${crop.crop_type}" required>
                <input type="date" name="planting_date" value="${crop.planting_date}" required>
                <input type="text" name="location" value="${crop.location}" required>
            `;
            showForm("编辑作物", fields);
            document.getElementById("edit-form").onsubmit = function(event) {
                event.preventDefault();
                updateCrop(id);
            };
        });
}

function updateCrop(id) {
    const csrfToken = document.querySelector("[name=csrfmiddlewaretoken]").value;
    const formData = new FormData(document.getElementById("edit-form"));
    const data = Object.fromEntries(formData.entries());

    fetch(`/update_crop/${id}/`, {
        method: "PUT",
        headers: {
            "Content-Type": "application/json",
            "X-CSRFToken": csrfToken
        },
        body: JSON.stringify(data)
    }).then(() => {
        closeForm();
        loadCrops();
    });
}

function deleteCrop(id) {
    const csrfToken = document.querySelector("[name=csrfmiddlewaretoken]").value;

    fetch(`/delete_crop/${id}/`, {
        method: "DELETE",
        headers: { "X-CSRFToken": csrfToken }
    }).then(() => loadCrops());
}

// 按此模式实现 Logs、Pests、Inspections 的增删改查。

// 默认加载作物信息
window.onload = function() {
    loadCrops();
};

function loadLogs() {
    currentView = "log";
    fetch("/get_logs/")
        .then(response => response.json())
        .then(data => {
            let tableHTML = `
                <h2>日志信息</h2>
                <button onclick="prepareAddLogForm()">添加日志</button>
                <table>
                    <tr>
                        <th>ID</th>
                        <th>种植日期</th>
                        <th>数量</th>
                        <th>位置</th>
                        <th>作物名称</th>
                        <th>操作</th>
                    </tr>
            `;
            data.data.forEach(log => {
                tableHTML += `
                    <tr>
                        <td>${log.id}</td>
                        <td>${log.planting_date}</td>
                        <td>${log.quantity}</td>
                        <td>${log.location}</td>
                        <td>${log.crop__name}</td>
                        <td>
                            <button onclick="editLog(${log.id})">编辑</button>
                            <button onclick="deleteLog(${log.id})">删除</button>
                        </td>
                    </tr>
                `;
            });
            tableHTML += `</table>`;
            document.getElementById("content").innerHTML = tableHTML;
        });
}

function prepareAddLogForm() {
    const fields = `
        <input type="date" name="planting_date" placeholder="种植日期" required>
        <input type="number" name="quantity" placeholder="数量" required>
        <input type="text" name="location" placeholder="位置" required>
        <input type="number" name="crop" placeholder="作物ID" required>
    `;
    showForm("添加日志", fields);
    document.getElementById("edit-form").onsubmit = addLog;
}

function addLog(event) {
    event.preventDefault();
    const csrfToken = document.querySelector("[name=csrfmiddlewaretoken]").value;
    const formData = new FormData(event.target);
    const data = Object.fromEntries(formData.entries());

    fetch("/add_log/", {
        method: "POST",
        headers: {
            "Content-Type": "application/json",
            "X-CSRFToken": csrfToken
        },
        body: JSON.stringify(data)
    }).then(() => {
        closeForm();
        loadLogs();
    });
}

function editLog(id) {
    fetch(`/get_log/${id}/`)
        .then(response => response.json())
        .then(log => {
            const fields = `
                <input type="date" name="planting_date" value="${log.planting_date}" required>
                <input type="number" name="quantity" value="${log.quantity}" required>
                <input type="text" name="location" value="${log.location}" required>
                <input type="number" name="crop" value="${log.crop}" required>
            `;
            showForm("编辑日志", fields);
            document.getElementById("edit-form").onsubmit = function(event) {
                event.preventDefault();
                updateLog(id);
            };
        });
}

function updateLog(id) {
    const csrfToken = document.querySelector("[name=csrfmiddlewaretoken]").value;
    const formData = new FormData(document.getElementById("edit-form"));
    const data = Object.fromEntries(formData.entries());

    fetch(`/update_log/${id}/`, {
        method: "PUT",
        headers: {
            "Content-Type": "application/json",
            "X-CSRFToken": csrfToken
        },
        body: JSON.stringify(data)
    }).then(() => {
        closeForm();
        loadLogs();
    });
}

function deleteLog(id) {
    const csrfToken = document.querySelector("[name=csrfmiddlewaretoken]").value;

    fetch(`/delete_log/${id}/`, {
        method: "DELETE",
        headers: { "X-CSRFToken": csrfToken }
    }).then(() => loadLogs());
}

function loadPests() {
    currentView = "pest";
    fetch("/get_pests/")
        .then(response => response.json())
        .then(data => {
            let tableHTML = `
                <h2>害虫信息</h2>
                <button onclick="prepareAddPestForm()">添加害虫信息</button>
                <table>
                    <tr>
                        <th>ID</th>
                        <th>害虫类型</th>
                        <th>成因</th>
                        <th>解决方案</th>
                        <th>操作</th>
                    </tr>
            `;
            data.data.forEach(pest => {
                tableHTML += `
                    <tr>
                        <td>${pest.id}</td>
                        <td>${pest.pest_type}</td>
                        <td>${pest.cause}</td>
                        <td>${pest.solution}</td>
                        <td>
                            <button onclick="editPest(${pest.id})">编辑</button>
                            <button onclick="deletePest(${pest.id})">删除</button>
                        </td>
                    </tr>
                `;
            });
            tableHTML += `</table>`;
            document.getElementById("content").innerHTML = tableHTML;
        });
}

function prepareAddPestForm() {
    const fields = `
        <input type="text" name="pest_type" placeholder="害虫类型" required>
        <textarea name="cause" placeholder="成因" required></textarea>
        <textarea name="solution" placeholder="解决方案" required></textarea>
    `;
    showForm("添加害虫信息", fields);
    document.getElementById("edit-form").onsubmit = addPest;
}

function addPest(event) {
    event.preventDefault();
    const csrfToken = document.querySelector("[name=csrfmiddlewaretoken]").value;
    const formData = new FormData(event.target);
    const data = Object.fromEntries(formData.entries());

    fetch("/add_pest/", {
        method: "POST",
        headers: {
            "Content-Type": "application/json",
            "X-CSRFToken": csrfToken
        },
        body: JSON.stringify(data)
    }).then(() => {
        closeForm();
        loadPests();
    });
}

function editPest(id) {
    fetch(`/get_pest/${id}/`)
        .then(response => response.json())
        .then(pest => {
            const fields = `
                <input type="text" name="pest_type" value="${pest.pest_type}" required>
                <textarea name="cause" required>${pest.cause}</textarea>
                <textarea name="solution" required>${pest.solution}</textarea>
            `;
            showForm("编辑害虫信息", fields);
            document.getElementById("edit-form").onsubmit = function(event) {
                event.preventDefault();
                updatePest(id);
            };
        });
}

function updatePest(id) {
    const csrfToken = document.querySelector("[name=csrfmiddlewaretoken]").value;
    const formData = new FormData(document.getElementById("edit-form"));
    const data = Object.fromEntries(formData.entries());

    fetch(`/update_pest/${id}/`, {
        method: "PUT",
        headers: {
            "Content-Type": "application/json",
            "X-CSRFToken": csrfToken
        },
        body: JSON.stringify(data)
    }).then(() => {
        closeForm();
        loadPests();
    });
}

function deletePest(id) {
    const csrfToken = document.querySelector("[name=csrfmiddlewaretoken]").value;

    fetch(`/delete_pest/${id}/`, {
        method: "DELETE",
        headers: { "X-CSRFToken": csrfToken }
    }).then(() => loadPests());
}

function loadInspections() {
    currentView = "inspection";
    fetch("/get_inspections/")
        .then(response => response.json())
        .then(data => {
            let tableHTML = `
                <h2>检测记录</h2>
                <button onclick="prepareAddInspectionForm()">添加检测记录</button>
                <table>
                    <tr>
                        <th>ID</th>
                        <th>检测日期</th>
                        <th>检测类型</th>
                        <th>结果</th>
                        <th>作物名称</th>
                        <th>检测员</th>
                        <th>操作</th>
                    </tr>
            `;
            data.data.forEach(record => {
                tableHTML += `
                    <tr>
                        <td>${record.id}</td>
                        <td>${record.inspection_date}</td>
                        <td>${record.inspection_type}</td>
                        <td>${record.result}</td>
                        <td>${record.crop__name}</td>
                        <td>${record.inspector__user__username}</td>
                        <td>
                            <button onclick="editInspection(${record.id})">编辑</button>
                            <button onclick="deleteInspection(${record.id})">删除</button>
                        </td>
                    </tr>
                `;
            });
            tableHTML += `</table>`;
            document.getElementById("content").innerHTML = tableHTML;
        });
}

function prepareAddInspectionForm() {
    const fields = `
        <input type="date" name="inspection_date" placeholder="检测日期" required>
        <input type="text" name="inspection_type" placeholder="检测类型" required>
        <textarea name="result" placeholder="结果" required></textarea>
        <input type="number" name="crop" placeholder="作物ID" required>
        <input type="number" name="inspector" placeholder="检测员ID" required>
    `;
    showForm("添加检测记录", fields);
    document.getElementById("edit-form").onsubmit = addInspection;
}

function addInspection(event) {
    event.preventDefault();
    const csrfToken = document.querySelector("[name=csrfmiddlewaretoken]").value;
    const formData = new FormData(event.target);
    const data = Object.fromEntries(formData.entries());

    fetch("/add_inspection/", {
        method: "POST",
        headers: {
            "Content-Type": "application/json",
            "X-CSRFToken": csrfToken
        },
        body: JSON.stringify(data)
    }).then(() => {
        closeForm();
        loadInspections();
    });
}

function editInspection(id) {
    fetch(`/get_inspection/${id}/`)
        .then(response => response.json())
        .then(record => {
            const fields = `
                <input type="date" name="inspection_date" value="${record.inspection_date}" required>
                <input type="text" name="inspection_type" value="${record.inspection_type}" required>
                <textarea name="result" required>${record.result}</textarea>
                <input type="number" name="crop" value="${record.crop}" required>
                <input type="number" name="inspector" value="${record.inspector}" required>
            `;
            showForm("编辑检测记录", fields);
            document.getElementById("edit-form").onsubmit = function(event) {
                event.preventDefault();
                updateInspection(id);
            };
        });
}

function updateInspection(id) {
    const csrfToken = document.querySelector("[name=csrfmiddlewaretoken]").value;
    const formData = new FormData(document.getElementById("edit-form"));
    const data = Object.fromEntries(formData.entries());

    fetch(`/update_inspection/${id}/`, {
        method: "PUT",
        headers: {
            "Content-Type": "application/json",
            "X-CSRFToken": csrfToken
        },
        body: JSON.stringify(data)
    }).then(() => {
        closeForm();
        loadInspections();
    });
}

function deleteInspection(id) {
    const csrfToken = document.querySelector("[name=csrfmiddlewaretoken]").value;

    fetch(`/delete_inspection/${id}/`, {
        method: "DELETE",
        headers: { "X-CSRFToken": csrfToken }
    }).then(() => loadInspections());
}

        </script>

</body>
</html> 
